-- UIDungeonInfo
-- Create by zouyb
-- 地牢信息界面

require "game/ui/misc/UIIndicator"

-- UIDungeonInfo继承自Layer
UIDungeonInfo = class("UIDungeonInfo", function()
    return cc.Layer:create();
end);

function UIDungeonInfo.create()
    return UIDungeonInfo.new();
end

-- 构造函数
function UIDungeonInfo:ctor()
    self:setName("UIDungeonInfo");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/dungeon/DungeonInfo.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册按钮点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 重绘
function UIDungeonInfo:redraw()
    local node = self.node;

    -- 区域标题
    local dungeonId = DungeonM.getDungeonId();
    local caption = findChildByName(node, "CT/caption");
    local parentId = DungeonAreaM.query(dungeonId, "parent_id");

    -- 如果是活动迷宫，显示活动名称
    if ActivityDungeonM.isActivityDungeon(dungeonId) then
        local activityCfg = ActivityDungeonM.getActivityByDungeonId(dungeonId);
        caption:setString(activityCfg["name"]);
    else
        if parentId ~= 0 then
            caption:setString(DungeonAreaM.query(parentId, "name"));
        else
            caption:setString(DungeonAreaM.query(dungeonId, "name"));
        end
    end

    TextStyleM.setTitleStyle(caption);

    -- 副标题
    local subHeadLabel = findChildByName(node, "CT/subhead");
    TextStyleM.setSubheadStyle(subHeadLabel);
    subHeadLabel:setVisible(true);
    local maxFloor = DungeonAreaM.query(dungeonId, "max_floor");

    if ActivityDungeonM.isActivityDungeon(dungeonId) then
        -- 如果是活动迷宫，显示难度
        local activity = ActivityDungeonM.getActivityByDungeonId(dungeonId);
        if activity == nil then
            error(string.format("获取不到迷宫(%d)的活动配置", dungeonId));
        end

        local str = ""
        if ActivityM.query(activity["id"], "rule") == "sky_activity" then
            local petId = activity["pet_id"];
            str = PetM.query(petId, "short_name");
        else
            local grade = activity["grade"];
            if grade == ACTIVITY_GRADE_EASY then
                str = getLocStr("activity_grade_easy");
            elseif grade == ACTIVITY_GRADE_NORMAL then
                str = getLocStr("activity_grade_normal");
            else
                str = getLocStr("activity_grade_difficult");
            end
        end
        subHeadLabel:setString(str);
    else
        if maxFloor == 0 then
            -- 无尽模式
            subHeadLabel:setString(getLocStr("endless_dungeon"));
        elseif SkyInstanceM.isInSkyInstance() then
            subHeadLabel:setString(getLocStr("sky_instance"));
        elseif AwakeM.isAwakeDungeon(dungeonId) then
            -- "限XXX冈布奥出战"
            local limitPet = DungeonAreaM.query(dungeonId, "limit_active_pet");
            subHeadLabel:setString(string.format(getLocStr("dungeon_limit_active_pet"), PetM.query(limitPet, "name")));
        else
            subHeadLabel:setString(DungeonAreaM.query(dungeonId, "name"));
        end
    end

    -- 区域说明
    local desc = findChildByName(node, "CT/desc");
    TextStyleM.setTextStyle(desc, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    desc:setString(DungeonAreaM.query(dungeonId, "desc"));


    local extraDesc = "";
    local extraDescLabel = findChildByName(node, "CT/extra_desc");
    TextStyleM.setTextStyle(extraDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);

    -- 迷宫层数
    if maxFloor > 0 then
        extraDesc = string.format(getLocStr("max_floor"), tostring(maxFloor).."F") .. "\n";
    end

    -- 迷宫事件图标显示
    local dungeonEventImg = findChildByName(node, "CT/dungeon_event");
    local eventLabel = findChildByName(node, "CT/event_label");
    local rudyImg = findChildByName(node, "CT/img_rudy");

    -- 获取该关卡的迷宫事件
    local parentId = DungeonAreaM.getParentId(dungeonId);
    local ids = AchievementM.getIdsByDungeonId(parentId);

    if #ids > 0 then
        -- 显示迷宫事件信息
        dungeonEventImg:setVisible(true);
        eventLabel:setVisible(true);
        TextStyleM.setTextStyle(eventLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -4, nil, nil, nil, nil, true);
        eventLabel:setString(getLocStr("dungeon_event"));
        rudyImg:setVisible(true);

        -- 宝石上下浮动
        local moveUp = cc.MoveBy:create(1, cc.p(0, 15));
        local moveDown = cc.MoveBy:create(1, cc.p(0, -15));
        local delayTime = cc.DelayTime:create(0.2);
        rudyImg:runAction(cc.RepeatForever:create(cc.Sequence:create(moveUp, moveDown, delayTime)));
    else
        -- 该关卡没有迷宫事件, 迷宫事件图标隐藏
        dungeonEventImg:setVisible(false);
        eventLabel:setVisible(false);
        rudyImg:setVisible(false);
    end

    -- 上次死亡
    local dungeonLegacy = ME.user.dbase:query("dungeon_legacy", {});
    local legacyInfo = dungeonLegacy[dungeonId];

    if legacyInfo and table.keys(legacyInfo)[1] ~= 0 then
        -- 有遗产信息
        extraDesc = extraDesc .. string.format(getLocStr("last_killed"), table.keys(legacyInfo)[1]) .. "\n";
    end

    -- 任务信息
    for _, taskInfo in ipairs(DailyTaskM.getTaskList()) do
        if taskInfo.dungeon_id == dungeonId then
            local curLayer = DungeonM.currentLayer();
            if curLayer > taskInfo.floor and taskInfo.is_finish == 0 then
                extraDesc = extraDesc .. string.format(getLocStr("task_info_cannot_finish"), taskInfo.floor, DailyTaskM.query(taskInfo.id, "name")) .. "\n";
            elseif taskInfo.is_finish ~= 0 then
                extraDesc = extraDesc .. string.format(getLocStr("task_info_finished"), taskInfo.floor, DailyTaskM.query(taskInfo.id, "name")) .. "\n";
            else
                extraDesc = extraDesc .. string.format(getLocStr("task_info"), taskInfo.floor, DailyTaskM.query(taskInfo.id, "name")) .. "\n";
            end
        end
    end

    if string.len(extraDesc) > 0 then
        extraDescLabel:setVisible(true);
        extraDescLabel = applyString(extraDescLabel, extraDesc);
        --extraDescLabel:setString(extraDesc);

        -- 与desc的文本位置自适应
        local extraPositionY = desc:getPositionY() - desc:getContentSize().height - 20;
        extraDescLabel:setPosition(extraDescLabel:getPositionX(), extraPositionY)
    else
        extraDescLabel:setVisible(false);
    end

    -- 重绘兑换按钮
    self:redrawBankExchange();

    -- 重绘暂离按钮
    self:redrawPauseButton();
end

-- 注册事件处理回调函数
function UIDungeonInfo:registerEventCallback()
    -- 注册银行兑换成功的事件
    EventMgr.register("UIDungeonInfo", event.BANK_EXCHANGE_DONE, function(args)
        local bonus = args.bonus
        local attrib = bonus[2];
        local amount = bonus[3];
        local fieldName = FieldsM.getFieldName(attrib);
        alert(string.format(getLocStr("dungeon_bank_exchange_ok"), fieldName, amount));

        -- 关闭当前界面
        --UIMgr.getCurrentScene():removeFormByName("UIDungeonInfo");
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIDungeonInfo", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIDungeonInfo" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_SP, TOPMENU_FRAME_GEM);
            UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
        end
    end);

    -- 注册冈布奥事件回调
    EventMgr.register("UIDungeonInfo", event.SLIME_EVENT, function(para)
        local eventId = para.eventId;
        if SlimeEventM.query(eventId, "rule") == "bank_exchange" then
            cclog("UIDungeonInfo 界面析构清理");

            UIMgr.getCurrentScene():removeFormByName("UIDungeonInfo");
            -- EventMgr.removeAll("UIDungeonInfo");
        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then

            -- 还原TopMenu的ZOrder
            local topMenu = UIMgr.getCurrentScene().topMenu;
            if topMenu then
                topMenu:setVisible(self.oldVisible);
                topMenu:setLocalZOrder(self.oldZOrder);
            end

            cclog("UIDungeonInfo 界面析构清理");

            EventMgr.removeAll("UIDungeonInfo");
        elseif ev == "enter" then
            -- 临时调高TOP_MENU的ZOrder
            local topMenu = UIMgr:getCurrentScene().topMenu;
            self.oldVisible = topMenu:isVisible();
            UIMgr.getCurrentScene().topMenu:setVisible(true);
            self.oldZOrder = topMenu:getLocalZOrder();
        end
    end);
end

-- 注册按钮点击事件
function UIDungeonInfo:registerTouchEvent()
    local node = self.node;

    -- 离开地牢
    local leaveBtn = findChildByName(node, "BT/leave_btn");
    leaveBtn:setTitleText(getLocStr("btn_text_end_dungeon"));
    local function onLeaveClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试离开
            self:tryLeave();

            -- 清除无用纹理
            UIMgr.clearUnusedTextures();
        end
    end
    leaveBtn:addTouchEventListener(onLeaveClick);
    TextStyleM.setTextStyle(leaveBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    -- 暂离地牢
    local pauseBtn = findChildByName(node, "BT/pause_btn");
    local function onLeaveClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            UIDungeonMgr.pauseDungeon();

            -- 清除无用纹理
            UIMgr.clearUnusedTextures();
        end
    end
    pauseBtn:addTouchEventListener(onLeaveClick);
    TextStyleM.setTextStyle(pauseBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    pauseBtn:setTitleText(getLocStr("pause_dungeon"));

    -- 新手关卡指引进行时，无法离开或暂离
    if not DungeonGuideM.isGuideFinished() then
        leaveBtn:setVisible(false);
        pauseBtn:setVisible(false);
    else
        leaveBtn:setVisible(true);
        pauseBtn:setVisible(true);
    end

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/close_btn");
    btnBack:setTitleText(getLocStr("btn_text_back"));
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIDungeonInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    -- 注册银行按钮点击事件
    local bankImg = findChildByName(node, "CT/dungeon_bank");
    local function onBankClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("dup_shop");

            self:doBankExchange();
        end
    end
    bankImg:addTouchEventListener(onBankClick);

    -- 注册迷宫事件点击
    local eventImg = findChildByName(node, "CT/dungeon_event");
    local function onEventClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 显示迷宫成就界面
            UIMgr.getCurrentScene():removeFormByName("UIDungeonAchiv");
            local dungeonId = DungeonM.getDungeonId();
            local parentId  = DungeonAreaM.getParentId(dungeonId);
            local uiDungeonAchiv = UIDungeonAchiv.create(parentId);
            UIMgr.getCurrentScene():addForm(uiDungeonAchiv);
            AudioM.playFx("ui_open1");
        end
    end
    eventImg:addTouchEventListener(onEventClick);
end

-- 银行兑换
function UIDungeonInfo:doBankExchange()
    local layer = DungeonM.currentLayer();

    -- 兑换消耗
    local costInfo = DungeonBankM.calcExchangeCost(layer);
    local costAttrib = costInfo[1];
    local costAmount = costInfo[2];

    -- 兑换可获得的钻石
    local gainInfo = DungeonBankM.getBonus(layer);
    local gainAmount = gainInfo[3];

    -- 当前已兑换次数
    local times = DungeonBankM.getExchangeTimes(layer);

    -- 兑换的逻辑处理
    local function tryExchange()
        local ret = DungeonBankM.canDoExchange(layer);
        if true ~= ret then
            closeFormByName("UIDungeonInfo");

            -- 显示钻石不足提示框
            showGemLackConfirm();
            return false;
        end
        return DungeonActionM.go("bank_exchange");
    end

    -- 弹出银行兑换确认框
    local msg = string.format(getLocStr("bank_exchange_confirm"), costAmount, gainAmount, times);
    confirm2(CONFIRM_TYPE_OK, getLocStr("bank_exchange"), msg,
             tryExchange, nil, getLocStr("btn_text_exhcange"));
end

-- 重绘暂离按钮
function UIDungeonInfo:redrawPauseButton()
    local pauseBtn = findChildByName(self.node, "BT/pause_btn");
    if DungeonM.hidePauseDungeon() then
        -- 如下情形不能点击暂离
        -- 1.副本   2.boss战     3.夹层迷宫  4.活动迷宫  5.天空特殊副本
        pauseBtn:setTouchEnabled(false);
        pauseBtn:setBright(false);
    else
        pauseBtn:setTouchEnabled(true);
        pauseBtn:setBright(true);
    end
end

-- 重绘探索点兑换信息
function UIDungeonInfo:redrawBankExchange()
    local bankImg = findChildByName(self.node, "CT/dungeon_bank");
    local spExchangeLabel = findChildByName(self.node, "CT/bank_label");

    -- 探索点兑换标题
    TextStyleM.setTextStyle(spExchangeLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -4, nil, nil, nil, nil, true);
    spExchangeLabel:setString(getLocStr("search_point_exchange"));

    -- 如果是在天空活动副本里，那么无法兑换探索点
    local dungeonId = DungeonM.getDungeonId();
    local activityInfo = ActivityDungeonM.getActivityByDungeonId(dungeonId);

    if type(activityInfo) == "table" then
        local activityId = activityInfo["id"];
        if ActivityM.query(activityId, "rule") == "sky_activity" then
            -- 探索点兑换置灰
            bankImg:setTouchEnabled(false);
            setGrayMode(bankImg, true);
            return;
        end
    end

    -- 如果在天空之城特殊副本中
    if SkyInstanceM.isInSkyInstance() then
        -- 探索点兑换置灰
        bankImg:setTouchEnabled(false);
        setGrayMode(bankImg, true);
    end

    -- 如果在觉醒地牢中
    if AwakeM.isInAwake() then
        -- 探索点兑换置灰
        bankImg:setTouchEnabled(false);
        setGrayMode(bankImg, true);
    end

    -- 如果商城未解锁，隐藏探索点兑换入口
    if not MarketM.isMarketFuncOpen() then
        bankImg:setVisible(false);
        spExchangeLabel:setVisible(false);
    else
        bankImg:setVisible(true);
        spExchangeLabel:setVisible(true);
    end
end

-- 尝试离开
function UIDungeonInfo:tryLeave()
    -- 如果不在副本中
    if not DungeonInstanceM.isInInstance() then
        -- 弹出离开迷宫确认提示框
        confirm2(CONFIRM_TYPE_OK_CANCEL, getLocStr("leave_dungeon"),
            getLocStr("leave_dungeon_confirm"), UIDungeonMgr.leaveDungeon);
            AudioM.playFx("button_spell");
        return;
    end

    local function leave()

        -- 弹出离开迷宫确认提示框
        confirm2(CONFIRM_TYPE_OK_CANCEL, getLocStr("leave_dungeon"),
            getLocStr("leave_dungeon_confirm"), UIDungeonMgr.leaveDungeon);
    end

    if DungeonInstanceM.isConfirmToLeave() then
        alert(getLocStr("leave_instance_confirm2"));
    else
        -- 离开
        leave();
    end
end

-- 适配
function UIDungeonInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


